package com.zhiwei.codesecurity.service.users;

import com.zhiwei.codesecurity.common.base.NullObjectResp;
import com.zhiwei.codesecurity.common.base.ServiceResponse;
import com.zhiwei.codesecurity.common.utils.*;
import com.zhiwei.codesecurity.entity.Users;
import com.zhiwei.codesecurity.mapper.UsersDao;
import com.zhiwei.codesecurity.mapper.UsersMapper;
import com.zhiwei.codesecurity.service.users.request.CheckLoginReq;
import com.zhiwei.codesecurity.service.users.request.LoginOutReq;
import com.zhiwei.codesecurity.service.users.request.LoginServReq;
import com.zhiwei.codesecurity.service.users.response.AddUserServRlt;
import com.zhiwei.codesecurity.service.users.response.LoginRlt;
import com.zhiwei.codesecurity.service.users.response.QueryUserServRlt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;

@Service("userService")
public class UserServiceImpl implements IUserService {
    private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    public ServiceResponse<AddUserServRlt> addUser(Users users) {
        logger.info(">>>>>> addUser start ... ");
        // 请求参数验证
        if (null == users) {
            logger.error("=== 请求参数为空|users= {}", users);
            return ServiceResponseUtil.createServiceResponseForParamError("请求参数为空!");
        }

        if (0 == usersDao.add(users)) {
            logger.error("=======添加用户失败========");
            return ServiceResponseUtil.createServiceResponseForBisError("添加用户失败!");
        }

        AddUserServRlt addUserServRlt = new AddUserServRlt();
        addUserServRlt.setUserId(users.getUserId());
        return ServiceResponseUtil.createServiceResponse(addUserServRlt);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    public ServiceResponse<NullObjectResp> modifyUser(Users users) {
        logger.info(">>>>>> modifyUser start ... ");
        // 请求参数验证
        if (null == users) {
            logger.error("=== 请求参数为空|users= {}", users);
            return ServiceResponseUtil.createServiceResponseForParamError("请求参数为空!");
        }

        Users usersNew = usersMapper.getByUserId(users.getUserId());
        if (null == usersNew) {
            logger.warn("=== 修改用户不存在|userId={}", users.getUserId());
            return ServiceResponseUtil.createServiceResponseForParamError("修改用户不存在!");
        }

        usersNew.setUserName(users.getUserName());
        usersNew.setUserMail(users.getUserMail());
        usersNew.setUserAccount(users.getUserAccount());
        usersNew.setUserPassword(users.getUserPassword());
        usersNew.setNote(users.getNote());
        usersNew.setUpdateTime(new Date());
        usersNew.setDataVersion(usersNew.getDataVersion() + 1);
        if (0 == usersDao.update(usersNew)) {
            logger.warn("=== 修改用户失败|userId={}", usersNew.getUserId());
            return ServiceResponseUtil.createServiceResponseForParamError("修改用户失败!");
        }
        return ServiceResponseUtil.createServiceResponse();
    }

    public ServiceResponse<QueryUserServRlt> queryUser(String userId) {
        logger.info(">>>>>> queryUser start ... ");
        // 请求参数验证
        if (StringUtils.isBlank(userId)) {
            logger.error("=== 请求参数为空|userId= {}", userId);
            return ServiceResponseUtil.createServiceResponseForParamError("请求参数为空!");
        }

        Users users = usersMapper.getByUserId(userId);
        if (null == users) {
            logger.warn("=== 修改用户不存在|userId={}", userId);
            return ServiceResponseUtil.createServiceResponseForParamError("查询的用户不存在!");
        }

        QueryUserServRlt queryUserServRlt = new QueryUserServRlt();
        BeanUtil.copyPropertiesQuietly(users, queryUserServRlt);

        return ServiceResponseUtil.createServiceResponse(queryUserServRlt);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    public ServiceResponse<NullObjectResp> deleteUser(String userId) {
        logger.info(">>>>>> deleteUser start ... ");
        // 请求参数验证
        if (StringUtils.isBlank(userId)) {
            logger.error("=== 请求参数为空|userId= {}", userId);
            return ServiceResponseUtil.createServiceResponseForParamError("请求参数为空!");
        }

        if (0 == usersMapper.delByUserId(userId)) {
            logger.warn("=== 删除用户不存在|userId={}", userId);
            return ServiceResponseUtil.createServiceResponseForParamError("删除用户不存在!");
        }

        return ServiceResponseUtil.createServiceResponse();
    }

    public ServiceResponse<LoginRlt> doLogin(LoginServReq loginServReq) {
        logger.info(">>>>>>>>开始执行登录操作:{}<<<<<<<<<<<<<<", loginServReq);

        // 检查用户是否存在及密码是否正确
        Users users = usersMapper.getUserByUserAccount(loginServReq.getLoginName());
        if (null == users) {
            logger.error("=====系统不存在该登录用户|用户账号:{}", loginServReq.getLoginName());
            return ServiceResponseUtil.createServiceResponseForParamError("系统不存在该登录用户!");
        }

        if (!loginServReq.getLoginPwd().equals(users.getUserPassword())) {
            logger.error("=====登录用户的账号或者密码不正确|用户账号:{}", loginServReq.getLoginName());
            return ServiceResponseUtil.createServiceResponseForParamError("登录用户的账号或者密码不正确!");
        }

        // 保存登录令牌到redis
        String tokenId = UUIDUtil.getUUID();
        String systemType = loginServReq.getSystemType();
        String sourceType = loginServReq.getSourceType();
        // redis中存入token信息
        redisUtil.delTokenId(systemType + "-" + users.getUserId(), tokenId, sourceType);
        redisUtil.setTokenId(systemType + "-" + users.getUserId(), tokenId, sourceType);

        LoginRlt loginRlt = new LoginRlt();
        loginRlt.setMemberNo(users.getUserId());
        loginRlt.setTokenId(tokenId);
        loginRlt.setUserName(users.getUserName());
        loginRlt.setUserMail(users.getUserMail());
        loginRlt.setTeamId(String.valueOf(users.getTeamId()));
        logger.info(">>>>>>>>用户登录成功:{}<<<<<<<<<<<<<<", loginRlt);
        return ServiceResponseUtil.createServiceResponse(loginRlt);
    }

    public ServiceResponse<Boolean> doIsLogin(CheckLoginReq checkLoginReq) {
        logger.info(">>>>>>>>开始执行检查是否登录操作:{}<<<<<<<<<<<<<<", checkLoginReq);
        if (null == checkLoginReq) {
            logger.error("=== 请求参数为空|checkLoginReq= {}", checkLoginReq);
            return ServiceResponseUtil.createServiceResponse(Boolean.FALSE);
        }

        String userId = checkLoginReq.getMemberNo();
        String systemType = ReloadAbleProperty.getProperty("codesecurity.partnerId");
        // 缓存中获取登录状态
        boolean flag = redisUtil.getTokenId(systemType + "-" + userId, checkLoginReq.getTokenId());
        logger.info(">>>>>>>>结束执行检查是否登录操作:{}<<<<<<<<<<<<<<", flag);
        return ServiceResponseUtil.createServiceResponse(flag);

    }

    public ServiceResponse<NullObjectResp> doLogout(LoginOutReq loginOutReq) {
        logger.info(">>>>>>>>开始执行退出登录操作:{}<<<<<<<<<<<<<<", loginOutReq);
        if (null == loginOutReq) {
            logger.error("=== 请求参数为空|loginOutReq= {}", loginOutReq);
            return ServiceResponseUtil.createServiceResponseForParamError("请求参数为空!");
        }

        String userId = loginOutReq.getMemberNo();
        String systemType = ReloadAbleProperty.getProperty("codesecurity.partnerId");
        String sourceType = loginOutReq.getSourceType();
        // 删除redis缓存中用户token信息
        redisUtil.delTokenId(systemType + "-" + userId, loginOutReq.getTokenId(), sourceType);
        logger.info(">>>>>>>>结束执行退出登录操作:{}<<<<<<<<<<<<<<");
        return ServiceResponseUtil.createServiceResponse();
    }

}
